use crate::message::*;
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
};

pub type RouterHandle = dyn Fn(&PayloadMessage) + Send + Sync;

#[derive(Clone, Default)]
pub struct Router {
    handles: Arc<Mutex<HashMap<String, Arc<RouterHandle>>>>,
}

impl Router {
    pub fn add_router(&mut self, uri: &str, event: &'static RouterHandle) {
        let mut binding = self.handles.lock().unwrap();
        binding.insert(uri.to_string(), Arc::new(event));
    }

    pub fn run(&mut self, payload: &PayloadMessage) {
        let binding = self.handles.lock().unwrap();
        let res = binding.get(payload.method.as_str());
        match res {
            Some(handle) => handle(payload),
            None => (), //println!("未找到该方法,原数据{:?}", payload),
        };
    }
}
